﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Linq.Expressions;
using Newtonsoft.Json.Linq;

using CanDoo;
using CanDoo.Core;
using CanDoo.Data;
using CanDoo.Web;
using CanDoo.FineUI;
using CanDoo.Extensions;
using CanDoo.Oil.Core.Models;
using CanDoo.Oil.Core.Contracts;
using CanDoo.Admin.Core.Contracts;
using FineUIPro;

namespace CanDoo.Oil.WebApp.storeInStoreOther
{
    public partial class Edit : EditPagebase<IInStoreOtherContract, InStoreOther>
    {
        public IUserContract UserContract { get; set; }
        public IWarehouseContract WarehouseContract { get; set; }
        private bool AppendToEnd = true;
        private int ShowRowCount = 10;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //FineUIListHelper.BindDDL<User>(UserContract.GetResolvedTree(), 0L, ed_User,true);
                //FineUIListHelper.BindDDL(UserContract.EntityName, this.UserContract.GetSelectList(), 0L, ed_User,true);
                //FineUIListHelper.BindDDL<User>(UserContract.GetResolvedTree(), 0L, ed_User,true);
                //FineUIListHelper.BindDDL(UserContract.EntityName, this.UserContract.GetSelectList(), 0L, ed_User,true);
                //FineUIListHelper.BindDDL<Warehouse>(WarehouseContract.GetResolvedTree(), 0L, ed_Warehouse,true);
                //FineUIListHelper.BindDDL(WarehouseContract.EntityName, this.WarehouseContract.GetSelectList(), 0L, ed_Warehouse,true);
                if (PageMode != pagemode.Add)
                    LoadData();
                #region 表格编辑  Page_Load
                // 删除选中单元格的客户端脚本
                string deleteScript = GetDeleteScript();

                JObject defaultObj = new JObject();

                defaultObj.Add("Price", ""); //单价
                defaultObj.Add("Num", ""); //数量
                defaultObj.Add("Money", ""); //金额
                defaultObj.Add("AlreadyNum", ""); //收货数量
                defaultObj.Add("AlreadyMoney", ""); //收货金额
                defaultObj.Add("Coefficient", ""); //出入库方向
                defaultObj.Add("Remark", ""); //备注

                defaultObj.Add("Delete", String.Format("<a href=\"javascript:;\" onclick=\"{0}\"><img src=\"{1}\"/></a>", deleteScript, IconHelper.GetResolvedIconUrl(Icon.Delete)));
                // 第一行新增一条数据
                btnNew.OnClientClick = GridChild.GetAddNewRecordReference(defaultObj, AppendToEnd);

                // 删除选中行按钮
                btnDelete.OnClientClick = GridChild.GetNoSelectionAlertReference("请至少选择一项！") + deleteScript;

                DB.KeepReading(() =>
                {
                    var ChildList = new List<InStoreOtherDetail>();
                    if (PageMode != pagemode.Add)
                    {
                        var m = Manager.GetById(EntityId);
                        if(m!=null)
                            ChildList = m.InStoreOtherDetails.ToList();
                    }
                    BindChild(ChildList);
                });
                #endregion
            }
        }

        #region 表格编辑
        private void BindChild(List<InStoreOtherDetail> childList)
        {
             var instoreotherdetailList = new List<InStoreOtherDetail>();
             if (childList != null)
             {
                 foreach (var m in childList)
                     instoreotherdetailList.Add(m);
             }
             for (int i = instoreotherdetailList.Count; i < ShowRowCount; i++)
             {
                 var m = new InStoreOtherDetail();
                 m.Id = 0L;
                 instoreotherdetailList.Add(m);
             }
             GridChild.DataSource = instoreotherdetailList;
             GridChild.DataBind();
        }

        // 删除选中行的脚本
        private string GetDeleteScript()
        {
            return Confirm.GetShowReference("删除选中行？", String.Empty, MessageBoxIcon.Question, GridChild.GetDeleteSelectedRowsReference(), String.Empty);
        }

        protected void GridChild_PreDataBound(object sender, EventArgs e)
        {
            // 设置LinkButtonField的点击客户端事件
            LinkButtonField deleteField = GridChild.FindColumn("Delete") as LinkButtonField;
            deleteField.OnClientClick = GetDeleteScript();
        }

        private OperationResult SaveChild(InStoreOther Entity)
        {
             if (Entity.InStoreOtherDetails == null)
                 Entity.InStoreOtherDetails = new List<InStoreOtherDetail>();
             var mEntities = Entity.InStoreOtherDetails;
            // 修改的现有数据
            Dictionary<int, Dictionary<string, object>> modifiedDict = GridChild.GetModifiedDict();
            foreach (int rowIndex in modifiedDict.Keys)
            {
                 var rowID = GridChild.DataKeys[rowIndex][0].ToLong();
                 if (rowID >  0L)
                 {
                     var mEntity = mEntities.FirstOrDefault(p => p.Id == rowID);

                     mEntity = UpdateDataRow(modifiedDict[rowIndex], mEntity);
                 }
                 else
                 {
                     InStoreOtherDetail mEntity = new InStoreOtherDetail();
                     mEntity.Id = IdMaker.NewId();
                     mEntity = UpdateDataRow(modifiedDict[rowIndex], mEntity);
                     mEntities.Add(mEntity);
                 }
            }

            // 删除现有数据
            List<int> deletedRows = GridChild.GetDeletedList();
            foreach (int rowIndex in deletedRows)
            {
                 var rowID = GridChild.DataKeys[rowIndex][0].ToLong();
                 if (rowID >  0L)
                 {
                     var item = mEntities.FirstOrDefault(p => p.Id == rowID);
                     mEntities.Remove(item);
                 }
            }

            // 新增数据
            List<Dictionary<string, object>> newAddedList = GridChild.GetNewAddedList();

            if (AppendToEnd)
            {
                for (int i = 0; i < newAddedList.Count; i++)
                {
                    InStoreOtherDetail mEntity = new InStoreOtherDetail();
                    mEntity.Id = IdMaker.NewId();
                    mEntity = UpdateDataRow(newAddedList[i], mEntity);
                    mEntities.Add(mEntity);
                }
            }
            else
            {
                for (int i = newAddedList.Count - 1; i >= 0; i--)
                {
                    InStoreOtherDetail mEntity = new InStoreOtherDetail();
                    mEntity.Id = IdMaker.NewId();
                    mEntity = UpdateDataRow(newAddedList[i], mEntity);
                    mEntities.Add(mEntity);
                }
            }
            return new OperationResult(OperationResultType.Success);
        }

        private InStoreOtherDetail UpdateDataRow(Dictionary<string, object> rowDict, InStoreOtherDetail mEntity)
        {
            if (rowDict.ContainsKey("Price"))
            {
                mEntity.Price = rowDict["Price"].ToDouble();
            }
            if (rowDict.ContainsKey("Num"))
            {
                mEntity.Num = rowDict["Num"].ToDouble();
            }
            if (rowDict.ContainsKey("Money"))
            {
                mEntity.Money = rowDict["Money"].ToDouble();
            }
            if (rowDict.ContainsKey("AlreadyNum"))
            {
                mEntity.AlreadyNum = rowDict["AlreadyNum"].ToDouble();
            }
            if (rowDict.ContainsKey("AlreadyMoney"))
            {
                mEntity.AlreadyMoney = rowDict["AlreadyMoney"].ToDouble();
            }
            if (rowDict.ContainsKey("Coefficient"))
            {
                mEntity.Coefficient = rowDict["Coefficient"].ToInt();
            }
            if (rowDict.ContainsKey("Remark"))
            {
                mEntity.Remark = rowDict["Remark"].ToString();
            }
            return mEntity;
        }
        #endregion
        protected override void LoadData(InStoreOther entity)
        {
            ed_Name.SetValue(entity.Name);
            ed_Code.SetValue(entity.Code);
            ed_InStoreDate.SetValue(entity.InStoreDate);
            if (entity.User!=null)
            {
                ed_User.Values=new string[] { entity.User.Id.ToString() };
                ed_User.Text=entity.User.Name;
            }
            if (entity.GiveUser!=null)
            {
                ed_GiveUser.Values=new string[] { entity.GiveUser.Id.ToString() };
                ed_GiveUser.Text=entity.GiveUser.Name;
            }
            ed_Warehouse.SetValue(entity.Warehouse);
            if (entity.Num!=null)
            {
                ed_Num.Values=new string[] { entity.Num.Id.ToString() };
                ed_Num.Text=entity.Num.Name;
            }
            ed_Money.SetValue(entity.Money);
            ed_Remark.SetValue(entity.Remark);
        }

        protected override OperationResult SaveData(InStoreOther entity)
        {
            entity.Name = ed_Name.GetValue().ToString();
            entity.Code = ed_Code.GetValue().ToString();
            entity.InStoreDate = ed_InStoreDate.GetValue().ToNullableDateTime();
            if(entity.InStoreDate ==DateTime.MinValue)
                entity.InStoreDate = null;
            if (ed_User.Values.Count() > 0 && ed_User.Values[0].ToLong() >  0L)
                entity.UserId = ed_User.Values[0].ToLong();
            else
                entity.UserId = 0L;
            if (ed_GiveUser.Values.Count() > 0 && ed_GiveUser.Values[0].ToLong() >  0L)
                entity.GiveUserId = ed_GiveUser.Values[0].ToLong();
            else
                entity.GiveUserId = 0L;
            entity.Warehouse = ed_Warehouse.GetValue().ToDouble();
            if (ed_Num.Values.Count() > 0 && ed_Num.Values[0].ToLong() >  0L)
                entity.NumId = ed_Num.Values[0].ToLong();
            else
                entity.NumId = 0L;
            entity.Money = ed_Money.GetValue().ToDouble();
            entity.Remark = ed_Remark.GetValue().ToString();
            SaveChild(entity);
            return base.SaveData(entity);
            
        }
    }
}
